<template>
  <div>
    <el-button @click="exportExcel">默认按钮</el-button>

    <el-table :data="pageData" stripe border height="500" style="width: 100%" id="tableDom">
      <el-table-column
        v-for="(item, index) in iTableColumn"
        :key="index"
        :width="item.width"
        :prop="item.field"
        :label="item.label"
        ref="zTable"
      ></el-table-column>
    </el-table>
    <zPagination @pageChanged="onPageChanged"></zPagination>
  </div>
</template>
<style scoped>
</style>
<script>
import FileSaver from 'file-saver'
import XLSX from 'xlsx'
import pageMixins from '@/views/common/pageMixins.js'
export default {
  name: 'zTablePlugin',
  mixins: [pageMixins],
  props: {
    tableData: {
      type: Object,
      default: {}
    },
    tableColumn: {
      type: Array,
      default: []
    }
  },
  watch: {
    'tableData.data': {
      deep: true,
      handler() {
        this.pageData = this.tableData.data
        this.onGotPageData({
          content: this.tableData.data,
          totalElements: Number(this.tableData.total),
          size: Number(this.tableData.pageSize),
          number: Number(this.tableData.currentPage)
        })
      }
    },
    tableColumn: {
      handler() {
        console.log('-=-=-=--=')
        console.log(this.tableColumn)
        this.iTableColumn = this.tableColumn
      }
    }
  },
  data() {
    return {
      iTtableData: this.tableData,
      pageData: this.tableData.data,
      iTableColumn: this.tableColumn
    }
  },
  mounted() {
    console.log(_.isEmpty(this.tableData))
    if (!_.isEmpty(this.tableData)) {
      this.onGotPageData({
        content: this.iTtableData.data,
        totalElements: Number(this.iTtableData.total),
        size: Number(this.iTtableData.pageSize),
        number: Number(this.iTtableData.currentPage)
      })
    }
  },
  methods: {
    exportExcel() {
      console.log('哈哈，开始导出')
      /* generate workbook object from table */
      var wb = XLSX.utils.table_to_book(document.querySelector('#tableDom'))
      /* get binary string as output */
      var wbout = XLSX.write(wb, {
        bookType: 'xlsx',
        bookSST: true,
        type: 'array'
      })
      try {
        FileSaver.saveAs(
          new Blob([wbout], { type: 'application/octet-stream' }),
          'sheetjs.xlsx'
        )
      } catch (e) {
        if (typeof console !== 'undefined') console.log(e, wbout)
      }
      return wbout
    }
  }
}
</script>
